<template>
  <div>
    <div v-loading="loadingData">
      <c-table-box ref="cTableBox" auto-height hide-func :setting="false" :data="tableData" :table-config="tableConfig" />
      <el-dialog
        v-if="showSelect"
        ref="refDlg"
        append-to-body
        title="包含品类"
        :visible.sync="showSelect"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="clearForm"
        width="700px"
        @close="closeDialog"
      >
        <FiledSelect
          ref="refSelect"
          v-model="filedTable"
          :props="{ label: 'categoryName', value: 'categoryCode' }"
          multiple
          :config="{
            title:'包含品类',
            interfacePath: '/api/v1/categoryAndSuperCategory/page',
            method:'post',
            filtersRaw:dialogFiltersRaw,
            paramsRaw:{},
            setting: [
              {
                prop: 'categoryCode',
                title: '品类编码'
              },
              {
                prop: 'categoryName',
                title: '品类名称'
              },
              {
                prop: 'parentCategoryCode',
                title: '上级品类编码'
              },
              {
                prop: 'parentCategoryName',
                title: '上级品类名称'
              }
            ]
          }"
        />
        <div slot="footer">
          <el-button size="mini" @click="closeDialog">取消</el-button>
          <el-button size="mini" type="primary" @click="handlerCategorys">确定</el-button>
        </div>
      </el-dialog>
    </div>

    <div class="btn-container">
      <c-button type="default" @click="prevHandle">上一步</c-button>
      <c-button type="primary" @click="saveHandle">保存</c-button>
      <c-button type="primary" @click="submitHandle">提交</c-button>
    </div>
  </div>
</template>
<script>
import { postCategoryInitialPage, postCategoryNumberPage, postAddCategoryNumber,
  postDetailCommit, postConfigSeriesPage, queryMainCategory } from '@/api/shopDrawing'
import { deepClone, otherFiltersItem } from '@/utils'
import FiledSelect from './components/FiledSelect.vue'
export default {
  name: 'Category',
  components: { FiledSelect },
  data() {
    return {
      loadingData: false,
      activeRow: {},
      dialogFiltersRaw: [],
      showSelect: false,
      filedTable: [],
      tableData: [],
      setting: [
        {
          prop: 'picTaskName',
          label: '所属图纸'
        },
        {
          prop: 'areaName',
          label: '所属区域'
        },
        {
          prop: 'spaceName',
          label: '所属空间'
        },
        {
          prop: 'styleName',
          label: '所属专区'
        },
        {
          prop: 'spaceTotalArea',
          label: '空间总面积'
        },
        {
          prop: 'seriesName',
          label: '系列名称'
        },
        {
          prop: 'categoryNames',
          label: '包含品类',
          render: (h, row) => {
            if (!row.flag) {
              row.flag = (Math.random() * 0xfffffffff).toString(16)
            }
            return h('el-input', {
              props: {
                value: row.categoryNames
              },
              attrs: {
                placeholder: '输入以搜索',
                flag: row.flag
              },
              on: {
                focus: v => {
                  this.handlerOpen(row)
                }
              }
            })
          }
        },
        {
          prop: 'categoryNumber',
          label: '品类数量',
          render: (h, row) => {
            return h('el-input-number', {
              props: {
                value: row.categoryNumber,
                min: 0
              },
              on: {
                input: v => {
                  this.$set(row, 'categoryNumber', v)
                }
              }
            })
          }
        }
      ],
      operator: [
        {
          prop: '',
          label: '操作',
          width: '80',
          render: (h, row) => {
            // if (row.add) {
            return h('el-button', {
              props: {
                type: 'text'
              },
              on: {
                click: () => {
                  this.removeHandle(row)
                }
              }
            }, '删除')
            // }
            // return h('span', '')
          }
        }
      ]
    }
  },
  computed: {
    tableConfig() {
      // return this.tableData.some(e => e.add) ? { setting: [...this.setting, ...this.operator] } : { setting: this.setting }
      // 全部可删除
      return { setting: [...this.setting, ...this.operator] }
    }
    // filtersRaw() {
    //   return Array.from(new Set(this.tableData.map(e => e.categoryCodes))).map(e => {
    //     return otherFiltersItem('code', e, '<>')
    //   })
    // }
  },
  created() {
    this.getData()
  },
  methods: {
    clearForm() {

    },
    closeDialog() {
      this.showSelect = false
    },
    // 打开品类选择弹窗
    async   handlerOpen(row) {
      if (row._$series) {
        const t = row._$series.map(e => e.seriesCode)
        row.seriesCode && !t.includes(row.seriesCode) ? t.push(row.seriesCode) : ''
        const filterRaw = [
          otherFiltersItem('saleSeriesCode', `[${t.join(',')}]`, 'in'),
          otherFiltersItem('isFinalLevel', `1`, '=')
        ]
        this.loadingData = true
        const resData = await queryMainCategory(filterRaw).catch(() => {
          this.loadingData = false
        })
        this.loadingData = false
        this.dialogFiltersRaw = resData
        this.showSelect = true
        this.activeRow = row
      }
      return []
    },
    // 处理品类
    handlerCategorys() {
      const v = this.$refs.refSelect.handleSubmit()
      const row = this.activeRow
      const f = (r, s) => `${r.picTaskCode}${r.spaceCode}${r.styleCode}${r.seriesCode}${r.categoryCodes}` === `${s.picTaskCode}${s.spaceCode}${s.styleCode}${s.seriesCode}${s.categoryCodes}`
      const td = this.tableData.filter(e => e !== row)
      if (v.length > 1) {
        const t = []
        for (let i = 0; i < v.length; i++) {
          const _row = deepClone(row)
          _row.categoryNames = v[i].parentCategoryName || v[i].categoryName
          _row.categoryCodes = v[i].parentCategoryCode || v[i].categoryCode
          _row.flag = (Math.random() * 0xfffffffff).toString(16)
          if (i !== 0) {
            _row.add = true
          }
          // console.log(td.some(e => f(_row, e)) || t.some(e => f(_row, e)), _row, row)
          if (td.some(e => f(_row, e)) || t.some(e => f(_row, e))) {
            this.$message.warning('空间、专区、系列与品类组合存在重复项！')
            this.updateRender(this.$children, row)
            return
          }
          t.push(_row)
        }
        this.tableData.splice(row.keyIndex, 1, ...t)
      } else if (v.length === 1) {
        const _row = deepClone(row)
        const tmp = v[0]
        _row.categoryNames = tmp.parentCategoryName || tmp.categoryName
        _row.categoryCodes = tmp.parentCategoryCode || tmp.categoryCode
        // console.log(row, _row)
        if (td.some(e => f(_row, e))) {
          this.$message.warning('系列与品类组合已存在！')
          this.updateRender(this.$children, row)
          return
        }
        this.$set(row, 'categoryNames', tmp.parentCategoryName || tmp.categoryName)
        this.$set(row, 'categoryCodes', tmp.parentCategoryCode || tmp.categoryCode)
      } else {
        this.$set(row, 'categoryNames', '')
        this.$set(row, 'categoryCodes', '')
      }
      this.closeDialog()
    },
    updateRender(children, row) {
      for (const child of children) {
        if ((child.$attrs || {}).flag === row.flag) {
          child.selLable = row.categoryNames
        } else if (child.$children instanceof Array) {
          this.updateRender(child.$children, row)
        }
      }
    },
    getData() {
      const otc = this.$route.query.outpicDetailTaskCode
      postCategoryNumberPage(otc).then(res => {
        if (res.data.records.length === 0) {
          return postCategoryInitialPage(otc)
        }
        return res
      }).then(res => {
        const styleCodes = res.data.records.map(e => e.styleCode)
        return postConfigSeriesPage(styleCodes).then(resSeries => {
          return [res, resSeries]
        })
      }).then(([res, resSeries]) => {
        const d = res.data.records.sort((a, b) => {
          const a1 = (a.areaIndex || 0) - (b.areaIndex || 0)
          const a2 = (a.spaceIndex || 0) - (b.spaceIndex || 0)
          const a3 = (a.styleIndex || 0) - (b.styleIndex || 0)
          return a1 !== 0 ? a1 : a2 !== 0 ? a2 : a3 !== 0 ? a3 : -1
        })
        // 合并数据。。。。。。。。。。。。。。。。。。。。。。
        const series = resSeries.data.records

        const seriesTmp = {}
        for (const s of series) {
          const k = `${s.bigStyleCode}`
          if (seriesTmp[k] === undefined) {
            seriesTmp[k] = []
          }
          seriesTmp[k].push(s)
        }
        for (const r of d) {
          const t = seriesTmp[`${r.styleCode}`]
          if (t) {
            r._$series = t
          }
        }
        d.sort((a, b) => {
          if (a.picTaskCode === undefined || b.picTaskCode === undefined) {
            return 1
          }
          a = parseInt(a.picTaskCode.replace(/[^0-9]/g, ''))
          b = parseInt(b.picTaskCode.replace(/[^0-9]/g, ''))
          if (isNaN(a) || isNaN(b)) {
            return 1
          }
          return a - b
        })
        this.tableData = d
      })
    },
    prevHandle() {
      this.$store.dispatch('views/goBack')
    },
    genData() {
      // 2.维护出图品类及数量，所有成品系列需控制必填：品类及数量必填；
      // categoryCodes categoryNumber
      for (let i = 0; i < this.tableData.length; i++) {
        const v = this.tableData[i]
        if (['Q014', 'Q015'].includes(v.areaCode)) {
          if (v.categoryCodes === '' || v.categoryCodes === undefined) {
            this.$message.warning(`请选择第${i + 1}行包含品类`)
            return Promise.reject('')
          }
          if (v.categoryNumber === '' || v.categoryNumber === undefined) {
            this.$message.warning(`请填写第${i + 1}行品类数量`)
            return Promise.reject('')
          }
        }
      }
      return Promise.resolve({
        designOutpicCategoryNumberDTOList: this.tableData.map(e => {
          const d = deepClone(e)
          delete d._$series
          delete d._$styleCode
          // const categorys = d.categorys || []
          // d.categoryNames = categorys.map(e => e.name).join(',')
          // d.categoryCodes = categorys.map(e => e.code).join(',')
          d.configSeriesId = d.configSeriesId || d.configProgramSeriesId
          // delete d.categorys
          delete d.add
          return d
        }),
        id: this.$route.query.id,
        outpicDetailTaskCode: this.$route.query.outpicDetailTaskCode
      })
    },
    saveHandle() {
      return this.genData().then(data => {
        return postAddCategoryNumber(data).then(res => {
          this.$message.success('保存成功！')
          this.$store.dispatch('views/goFirst')
        })
      })
    },
    submitHandle() {
      return this.genData().then(data => {
        return postDetailCommit(data).then(res => {
          this.$message.success('提交成功！')
          this.$store.dispatch('views/goFirst')
        })
      })
    },
    removeHandle(row) {
      this.tableData.splice(row.keyIndex, 1)
    },
    async  getFiltersRaw(row) {
      if (row._$series) {
        const t = row._$series.map(e => e.seriesCode)
        row.seriesCode && !t.includes(row.seriesCode) ? t.push(row.seriesCode) : ''
        const filterRaw = [
          otherFiltersItem('saleSeriesCode', `[${t.join(',')}]`, 'in'),
          otherFiltersItem('isFinalLevel', `1`, '=')
        ]
        const resData = await queryMainCategory(filterRaw).catch(() => {
          this.loadingData = false
        })
        console.log('筛选数据', resData)
        this.showSelect = true
        return resData
      }
      return []
    }
  }
}
</script>
